package com.shuaiche.yeguan.ui.common;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnErrorListener;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.listener.OnPageErrorListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shuaiche.yeguan.R;
import com.shuaiche.yeguan.util.FileUtils;
import com.shuaiche.yeguan.util.StringUtils;
import com.shockwave.pdfium.PdfDocument;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;

public class PdfPreviewActivity extends AppCompatActivity implements View.OnClickListener {

    RelativeLayout rl_back;
    PDFView pdfView;
    TextView tvError;
    private String localPath;
    private Uri fileUri;
    private String netUrl;

    private int pageNumber = 0;
    private String pdfFileName;


    private boolean chaType;
    private boolean fromTestReport;

    private String carName;
    private String vin;
    private String imgLogo;
    private boolean showShare;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Window window = getWindow();
        window.getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        );

        setContentView(R.layout.activity_pdf_preview);

        pdfView = findViewById(R.id.pdfView);
        tvError = findViewById(R.id.tv_hit_for_error);
        rl_back = findViewById(R.id.rl_back);

        rl_back.setOnClickListener(this);

        getData();
        showPDF();

    }

    private void showPDF() {
        if (!StringUtils.isEmpty(netUrl)) {
            // 网络url显示分享
            chaType = true;
            int positon_x = netUrl.lastIndexOf(File.separator);
            pdfFileName = netUrl.substring(positon_x + 1, netUrl.length());
            getNetWorkPDF(netUrl);
        } else if (fileUri != null) {
            // 本地url不显示分享
            chaType = false;
//            int positon_x = localPath.lastIndexOf(File.separator);
//            pdfFileName = localPath.substring(positon_x + 1, localPath.length());
            pdfFileName = FileUtils.getFileNameByUri(this,fileUri);
            try {

                pdfView.fromUri(fileUri)   //设置pdf文件地址
//                        .invalidPageColor(R.color.white)
                        .defaultPage(pageNumber)
                        .onPageChange(new OnPageChangeListener() {
                            @Override
                            public void onPageChanged(int page, int pageCount) {
                                pageNumber = page;
//                                setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
//                                Log.e("chj", "setTitle = " + String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
                            }
                        })
                        .enableSwipe(false)
                        .enableAnnotationRendering(true)
                        .onLoad(new OnLoadCompleteListener() {
                            @Override
                            public void loadComplete(int nbPages) {
                                tvError.setVisibility(View.GONE);
//                                loadingView.loadSuccess(0, null);
                                PdfDocument.Meta meta = pdfView.getDocumentMeta();

                                printBookmarksTree(pdfView.getTableOfContents(), "-");
                            }
                        })
                        .scrollHandle(new DefaultScrollHandle(PdfPreviewActivity.this))
//                        .scrollHandle(null)
                        .spacing(0) // in dp
                        .onError(new OnErrorListener() {
                            @Override
                            public void onError(Throwable t) {
                                Log.e("chj", "onError");
                                tvError.setVisibility(View.VISIBLE);


                            }
                        })
                        .onPageError(new OnPageErrorListener() {
                            @Override
                            public void onPageError(int page, Throwable t) {
                                Log.e("chj", "onPageError");
                            }
                        })
//                .pageFitPolicy(FitPolicy.BOTH)
                        .load();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    private void getNetWorkPDF(String url) {
        final InputStream[] input = new InputStream[1];
        new AsyncTask<Void, Void, Void>() {
            @SuppressLint({"WrongThread", "StaticFieldLeak"})
            @Override
            protected Void doInBackground(Void... voids) {
                try {
                    input[0] = new URL(url).openStream();
//                    input[0] = new URL("https://img.shuaiche.com/temp/file/car/testreport/2321537b7a975ab547a594cd4bbf941e.txt").openStream();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                pdfView.fromStream(input[0])
//                        .pageFitPolicy(FitPolicy.WIDTH)
                        .onPageChange(new OnPageChangeListener() {
                            @Override
                            public void onPageChanged(int page, int pageCount) {
                                pageNumber = page;
//                                setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
//                                Log.e("chj", "setTitle = " + String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
                            }
                        })
                        .onLoad(new OnLoadCompleteListener() {
                            @Override
                            public void loadComplete(int nbPages) {
                                tvError.setVisibility(View.GONE);
                                PdfDocument.Meta meta = pdfView.getDocumentMeta();
                                printBookmarksTree(pdfView.getTableOfContents(), "-");
                            }
                        })
                        .onError(new OnErrorListener() {
                            @Override
                            public void onError(Throwable t) {
                                Log.e("chj", "onError");
//                                loadingView.loadFail(0, 0, "");
                                tvError.setVisibility(View.VISIBLE);


                            }
                        })
                        .onPageError(new OnPageErrorListener() {
                            @Override
                            public void onPageError(int page, Throwable t) {
                                Log.e("chj", "onPageError");
                            }
                        })
                        .load();
            }
        }.execute();
    }

    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

//            Log.e("chj", String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }

    private void getData() {
        if (getIntent() != null) {
            fileUri = getIntent().getParcelableExtra("localPath");
            netUrl = getIntent().getStringExtra("netUrl");
            fromTestReport = getIntent().getBooleanExtra("fromTestReport",false);
            carName = getIntent().getStringExtra("carName");
            vin = getIntent().getStringExtra("vin");
            imgLogo = getIntent().getStringExtra("imgLogo");
            showShare = getIntent().getBooleanExtra("showShare",true);

        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.rl_back){
            finish();
        }
    }
}